home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_12_06 / allison / ctrlc.c < prev    next >
C/C++ Source or Header  |  1994-04-08  |  854b  |  51 lines

  1. LISTING 12 - A safe SIGINT handler that counts keyboard
  2. interrupts
  3.  
  4. /* ctrlc.c:    A safe SIGINT handler */
  5. #include <stdio.h>
  6. #include <signal.h>
  7.  
  8. void ctrlc_handler(int sig);
  9.  
  10. volatile sig_atomic_t ccount = 0;
  11.  
  12. main()
  13. {
  14.     char buf[BUFSIZ];
  15.  
  16.     /* Install SIGINT handler */
  17.     if (signal(SIGINT,ctrlc_handler) == SIG_ERR)
  18.         fputs("Error installing ctrlc handler\n",stderr);
  19.  
  20.     /* Do some I/O */
  21.     while (gets(buf))
  22.         puts(buf);
  23.  
  24.     /* Restore default handler */
  25.     signal(SIGINT,SIG_DFL);
  26.     printf("You pressed ctrlc %d times\n",ccount);
  27.     return 0;
  28. }
  29.  
  30. void ctrlc_handler(int sig)
  31. {
  32.     /* Re-install handler immediately */
  33.     signal(sig,ctrlc_handler);
  34.  
  35.     ++ccount;
  36.     return;
  37. }
  38.  
  39. /* Sample Execution
  40. c:>ctrlc
  41. hello
  42. hello
  43. ^C
  44. there
  45. there
  46. ^C
  47. ^Z
  48. You pressed ctrlc 2 times
  49. */
  50.  
  51.